<template>
  <div
    ref="tooltipEditor"
    class="tooltip-editor"
  >
    <el-button
      :link="true"
      type="primary"
      size="default"
      icon="Tools"
      @click="openEditor"
    >
      {{ btnText }}
    </el-button>
    <div
      v-show="editorVisiable"
      ref="popBox"
      :class="`pop-box for_${useFor} dialog_style_${componentStyle}`"
    >
      <el-dialog
        ref="editorDialog"
        v-model="editorVisiable"
        :title="btnText"
        width="1170px"
        :close-on-click-modal="false"
        :class="`${visualThemeClassName} ${xvueNameSpace}`"
        @close="cancelEditor"
      >
        <div class="tip">
          <div
            v-show="useFor === 'hover-text'"
            class="top-btn"
          >
            <el-button
              class="add-api-item btn-sure"
              type="primary"
              size="default"
              icon="CirclePlus"
              @click="newApiItem"
            >
              {{ $demoi18n('panel.tooltipEditor.btnVariable') }}
            </el-button>
          </div>

          <div
            v-show="isAsTooltipOptShow"
            class="row-box switch"
          >
            <div class="label">
              <el-tooltip
                :content="$demoi18n('panel.label.asTooltip')"
                placement="top"
                :effect="xvueTheme"
              >
                <span>{{ $demoi18n('panel.label.asTooltip') }}</span>
              </el-tooltip>
              <Helptip>{{ $demoi18n('panel.label.asTooltipHelptip') }}</Helptip>
            </div>
            <div class="cont">
              <el-switch v-model="form.asTooltip"></el-switch>
            </div>
          </div>

          <template v-if="form.asTooltip">
            <div
              v-show="useFor !== 'hover-text'"
              class="row-box"
            >
              <div class="label">
                <el-tooltip
                  content="Tooltip Key"
                  placement="top"
                  :effect="xvueTheme"
                >
                  <span>Tooltip Key</span>
                </el-tooltip>
                <Helptip>{{ $demoi18n('panel.label.tooltipKey.helptip') }}</Helptip>
              </div>
              <div class="cont">
                <ValueInputer v-model:value="form.asTooltipKey" />
              </div>
            </div>
          </template>

          <template v-else>
            <div
              v-show="useFor === 'tooltip' && type !== 'echart'"
              class="row-box switch"
            >
              <div class="label">
                <el-tooltip
                  :content="$demoi18n('panel.tooltipEditor.showTooltip')"
                  placement="top"
                  :effect="xvueTheme"
                >
                  <span>{{ $demoi18n('panel.tooltipEditor.showTooltip') }}:</span>
                </el-tooltip>
              </div>
              <div class="cont">
                <el-switch v-model="form.isVisiable"></el-switch>
                <span
                  class="advancedSetting"
                  @click="advancedSettingVisiable = true"
                >
                  <el-icon><Tools /></el-icon>
                </span>
              </div>
            </div>

            <div
              v-show="type === 'echart'"
              class="row-box switch"
            >
              <div class="label">
                <el-tooltip
                  :content="$demoi18n('panel.tooltipEditor.advancedTooltip')"
                  placement="top"
                  :effect="xvueTheme"
                >
                  <span>{{ $demoi18n('panel.tooltipEditor.advancedTooltip') }}:</span>
                </el-tooltip>
              </div>
              <div class="cont">
                <el-switch v-model="form.isVisiable"></el-switch>
                <span class="info"></span>
                <span
                  class="advancedSetting"
                  @click="advancedSettingVisiable = true"
                >
                  <el-icon><Tools /></el-icon>
                </span>
              </div>
            </div>
            <div
              v-show="type === 'echart'"
              class="row-box switch"
            >
              <div class="label">
                <el-tooltip
                  :content="$demoi18n('panel.tooltipEditor.aativeTooltip')"
                  placement="top"
                  :effect="xvueTheme"
                >
                  <span>{{ $demoi18n('panel.tooltipEditor.aativeTooltip') }}:</span>
                </el-tooltip>
              </div>
              <div class="cont">
                <el-switch v-model="form.isOriginVisiable"></el-switch>
                <span class="info"></span>
                <span
                  class="originSetting"
                  @click="originSettingVisiable = true"
                >
                  <el-icon><Tools /></el-icon>
                </span>
              </div>
            </div>
            <div
              v-show="useFor === 'tooltip'"
              class="row-box switch"
            >
              <div class="label">
                <el-tooltip
                  :content="$demoi18n('panel.tooltipEditor.permil')"
                  placement="top"
                  :effect="xvueTheme"
                >
                  <span>{{ $demoi18n('panel.tooltipEditor.permil') }}:</span>
                </el-tooltip>
              </div>
              <div class="cont">
                <el-switch v-model="form.isPermil"></el-switch>
              </div>
            </div>

            <!-- 默认变量 -->
            <div
              v-show="useFor === 'tooltip'"
              class="row-box default-vars"
            >
              <div class="label">
                <el-tooltip
                  :content="$demoi18n('panel.tooltipEditor.defaultVariable')"
                  placement="top"
                  :effect="xvueTheme"
                >
                  <span>{{ $demoi18n('panel.tooltipEditor.defaultVariable') }}:</span>
                </el-tooltip>
              </div>
              <div class="cont">
                <div class="list">
                  <span
                    v-for="(n, i) in varsNew"
                    :key="i"
                    class="var"
                    @click="insertText(`$\{${i}\}`)"
                  >
                    {{ `$\{${i}\}` }}
                  </span>
                </div>
                <div class="var_desc">
                  <HelpManualSnippet
                    :snippet-key="`tooltip_vars.${compKey}`"
                    :box-style="{ padding: '5px' }"
                  />
                </div>
              </div>
              <el-button
                class="add-api-item btn-sure"
                type="primary"
                size="small"
                icon="CirclePlus"
                @click="newApiItem"
              >
                {{ $demoi18n('panel.tooltipEditor.btnVariable') }}
              </el-button>
              <el-button
                v-if="newAsItemBtnShow"
                class="add-api-item btn-sure"
                type="primary"
                size="small"
                icon="CirclePlus"
                @click="newAsItem"
              >
                {{ $demoi18n('panel.label.component') }}
              </el-button>
            </div>

            <!-- api变量信息 -->
            <div class="api-vars">
              <div
                v-for="(item, i) in form.apis"
                :key="i"
                class="row-box"
              >
                <div class="label">
                  <el-tooltip
                    :content="`${$demoi18n('panel.tooltipEditor.dataSource')}${i + 1}`"
                    placement="top"
                    :effect="xvueTheme"
                  >
                    <span>{{ $demoi18n('panel.tooltipEditor.dataSource') }}{{ i + 1 }}:</span>
                  </el-tooltip>
                </div>
                <div class="cont api-item">
                  <div class="api-message">
                    <span class="api-message-label">{{ $demoi18n('panel.label.dataSourceType') }}:</span>
                    <span class="api-message-value">
                      {{ item.dataSourceType_label }}
                    </span>
                    <span class="api-message-label">{{ $demoi18n('panel.tooltipEditor.dataSource') }}:</span>
                    <span class="api-message-value">
                      {{ item.dataSource_label }}
                    </span>
                    <span class="api-message-label">API:</span>
                    <span class="api-message-value">
                      {{ item.apiCode_label }}
                    </span>
                  </div>
                  <div class="data-correlation">
                    <span>{{ $demoi18n('panel.tooltipEditor.dataCorrelate') }}:</span>
                    <div
                      v-if="item.correlation === 'correlate'"
                      class="correlate"
                    >
                      <span
                        v-for="(cItem, cIndex) in item.correlatedData"
                        :key="cIndex"
                        class="correlate-item"
                      >
                        <span class="priKey">{{ `$\{${cItem.priKey}\}` }}</span>
                        <span class="symbol">=</span>
                        <span class="priMapKey">
                          {{ `$\{v${i + 1}.${cItem.priMapKey_label}\}` }}
                        </span>
                      </span>
                    </div>
                    <span v-else>{{ $demoi18n('panel.tooltipEditor.noDataCorrelate') }}</span>
                  </div>
                  <div class="inner">
                    <span>{{ $demoi18n('panel.tooltipEditor.optionalVariables') }}:</span>
                    <span
                      v-for="(v, vIndex) in item.apiFields"
                      :key="vIndex"
                      class="var"
                      :title="v.option_label"
                      @click="insertText(`$\{v${i + 1}.${v.option_label}\}`)"
                    >
                      {{ `$\{v${i + 1}.${v.option_label}\}` }}
                    </span>
                  </div>
                  <div class="tool">
                    <el-button
                      :link="true"
                      type="primary"
                      icon="EditPen"
                      @click="editApiItem(item)"
                    ></el-button>
                    <el-button
                      :link="true"
                      type="primary"
                      icon="Delete"
                      @click="delApiItem(item)"
                    ></el-button>
                  </div>
                </div>
              </div>
            </div>

            <!-- 组件级tooltip -->
            <div class="asTooltipUsers">
              <div
                v-for="(item, i) in form.asTooltipUsers"
                :key="i"
                class="row-box"
              >
                <div class="label">
                  <el-tooltip
                    :content="`${$demoi18n('panel.label.component')}${i + 1}`"
                    placement="top"
                    :effect="xvueTheme"
                  >
                    <span>{{ $demoi18n('panel.label.component') }}{{ i + 1 }}:</span>
                  </el-tooltip>
                </div>
                <div class="cont as-item">
                  <div class="data-correlation">
                    <span>{{ $demoi18n('panel.tooltipEditor.dataCorrelate') }}:</span>
                    <div
                      v-if="item.correlation === 'correlate'"
                      class="correlate"
                    >
                      <span
                        v-for="(cItem, cIndex) in item.correlatedData"
                        :key="cIndex"
                        class="correlate-item"
                      >
                        <span class="priKey">{{ `$\{${cItem.priKey}\}` }}</span>
                        <span class="symbol">=</span>
                        <span class="priMapKey">
                          {{ `$\{${cItem.priMapKey}\}` }}
                        </span>
                      </span>
                    </div>
                    <span v-else>{{ $demoi18n('panel.tooltipEditor.noDataCorrelate') }}</span>
                  </div>
                  <div class="inner">
                    <Helptip>{{ $demoi18n('panel.label.placeholderVariable.helptip') }}</Helptip>
                    <span>{{ $demoi18n('panel.label.placeholderVariable') }}:</span>
                    <span
                      class="var"
                      @click="insertText(`@\{${item.asTooltipKey}\}`)"
                    >{{
                      `@\{${item.asTooltipKey}\}`
                    }}</span>
                  </div>
                  <div class="tool">
                    <el-button
                      :link="true"
                      type="primary"
                      icon="EditPen"
                      @click="editAsItem(item)"
                    ></el-button>
                    <el-button
                      :link="true"
                      type="primary"
                      icon="Delete"
                      @click="delAsItem(item)"
                    ></el-button>
                  </div>
                </div>
              </div>
            </div>

            <div class="demo">
              <div class="code">
                <div>
                  {{ $demoi18n('panel.toolTipEditor.exampleTip') }}
                  <br />{{ $demoi18n('panel.tooltipEditor.variableUsageRef') }}:
                  <span
                    v-if="!demoDetailVisible"
                    class="expand_btn"
                    @click="demoDetailVisible = true"
                  ><el-icon><ArrowRight /></el-icon></span>
                  <span
                    v-else
                    class="expand_btn"
                    @click="demoDetailVisible = false"
                  ><el-icon><ArrowDown /></el-icon></span>
                </div>
                <table v-if="demoDetailVisible">
                  <tr>
                    <th>{{ $demoi18n('word.variable') }}:</th>
                    <td>${variable}</td>
                  </tr>
                  <tr>
                    <th>{{ $demoi18n('panel.tooltipEditor.arrayVariableSubitem') }}:</th>
                    <td>${arr[2]}</td>
                  </tr>
                  <tr>
                    <th>{{ $demoi18n('panel.tooltipEditor.objectVariableSubitem') }}:</th>
                    <td>${obj.name}</td>
                  </tr>
                  <tr>
                    <th>{{ $demoi18n('word.mix') }}:</th>
                    <td>${arr[2].name}</td>
                  </tr>
                  <tr>
                    <th>{{ $demoi18n('word.calculationFormula') }}:</th>
                    <td>
                      {{ $demoi18n('panel.tooltipEditor.formulaTip') }}
                    </td>
                  </tr>
                  <tr>
                    <th>{{ $demoi18n('panel.tooltipEditor.ifBlockTip') }}:</th>
                    <td>
                      #--- if ${value} ---#
                      <br />{{ $demoi18n('panel.tooltipEditor.ifBlockTipInner') }} <br />#--- end if ---#
                    </td>
                  </tr>
                </table>

                <HelpManual
                  v-if="useFor === 'tooltip'"
                  link="tooltip-setting"
                  mode="single_link"
                >{{
                  $demoi18n('tooltip-editor.moreHelp')
                }}</HelpManual>
              </div>
            </div>
          </template>
        </div>
        <TinymceEditor
          v-if="!form.asTooltip && editorVisiable"
          ref="TinymceEditor"
          :html="form.html"
          :useFor="useFor"
          :theme="xvueTheme"
          @save="saveEditor"
          @cancel="cancelEditor"
        />
        <div
          v-show="form.asTooltip"
          class="btns"
        >
          <el-button
            class="btn-sure"
            size="default"
            type="primary"
            @click="saveEditor('')"
          >
            {{ $demoi18n('btn.save') }}
          </el-button>
          <el-button
            class="button-cancel"
            size="default"
            @click="cancelEditor()"
          >
            {{ $demoi18n('btn.cancel') }}
          </el-button>
        </div>
      </el-dialog>
      <el-dialog
        v-model="dataDialogVisiable"
        :title="dataDialogTitle"
        width="450px"
        :close-on-click-modal="false"
        :class="`${visualThemeClassName} ${xvueNameSpace}`"
        @open="openTooltipData"
        @close="cancelApiItem"
      >
        <TooltipData
          v-if="dataDialogVisiable"
          ref="tooltip_data"
          :main-vars="varsNew"
          :api-conf="curApiItem"
          :use-for="useFor"
          :extra-config="extraConfig"
          :show-correlation="showCorrelation"
          :widget-instance-id="widgetInstanceId"
          @save="saveApiItem"
          @cancel="cancelApiItem"
        />
      </el-dialog>
      <el-dialog
        v-model="asTooltipDialogVisible"
        class="asTooltip_dialog"
        :title="asTooltipDialogTitle"
        append-to-body
        :close-on-click-modal="false"
        :class="`${visualThemeClassName} ${xvueNameSpace}`"
        @close="cancelAsItem"
      >
        <AsTooltipData
          v-if="asTooltipDialogVisible"
          :main-vars="varsNew"
          :as-item="curAsItem"
          @save="saveAsItem"
          @cancel="cancelAsItem"
        />
      </el-dialog>
      <el-dialog
        v-model="advancedSettingVisiable"
        class="advancedSettingDialog"
        :title="$demoi18n('panel.tooltipEditor.advancedTooltip')"
        append-to-body
        width="450px"
        :close-on-click-modal="false"
        :class="`${visualThemeClassName} ${xvueNameSpace}`"
        @close="closeAdvancedTooltipDialog"
      >
        <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" />
        <el-form
          v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
          class="prop-form"
          label-position="right"
          label-width="110px"
        >
          <VsFormItem
            :label="$demoi18n('layer.label.duration')"
            style="display:flex;align-items:center;"
            :rules="genRulesByKey('tooltip.hideDelay')"
          >
            <Range
              v-model:value="form.hideDelay"
              :min="0"
              :max="100"
              type="input"
            />
          </VsFormItem>
          <VsFormItem
            :label="$demoi18n('layer.label.bgColor')"
            style="display:flex;align-items:center;"
            :rules="genRulesByKey('tooltip.advancedTooltipSetting.background')"
          >
            <ColorPicker
              v-model:value="form.advancedTooltipSetting.background"
              :show-alpha="true"
              @change="colorChange"
            />
          </VsFormItem>
          <VsFormItem
            :label="$demoi18n('layer.label.borderColor')"
            style="display:flex;align-items:center;"
            :rules="genRulesByKey('tooltip.advancedTooltipSetting.borderColor')"
          >
            <ColorPicker
              v-model:value="form.advancedTooltipSetting.borderColor"
              :show-alpha="true"
              @change="color => (form.advancedTooltipSetting.borderColor = color)"
            />
          </VsFormItem>
          <VsFormItem
            :label="$demoi18n('layer.label.borderWidth')"
            style="display:flex;align-items:center;"
            :rules="genRulesByKey('tooltip.advancedTooltipSetting.borderWidth')"
          >
            <Range
              v-model:value="form.advancedTooltipSetting.borderWidth"
              :min="0"
              :max="100"
              type="input"
            />
          </VsFormItem>
          <div
            class="padding-box"
            style="display:flex;"
          >
            <label
              class="padding-box-label el-form-item__label"
              style="box-sizing:border-box;padding-right:12px;text-align:right;line-heigth:40px;width:130px;"
            >{{ $demoi18n('layer.label.padding') }}</label>
            <div
              class="padding-box-content"
              style="display:flex;flex:1;flex-wrap:wrap;"
            >
              <VsFormItem
                class="padding-box-item"
                label="T"
                :rules="genRulesByKey('tooltip.advancedTooltipSetting.padding.[x]')"
              >
                <Range
                  v-model:value="form.advancedTooltipSetting.paddingArr[0]"
                  :min="0"
                  :max="100"
                  type="input"
                />
              </VsFormItem>
              <VsFormItem
                class="padding-box-item"
                label="R"
                :rules="genRulesByKey('tooltip.advancedTooltipSetting.padding.[x]')"
              >
                <Range
                  v-model:value="form.advancedTooltipSetting.paddingArr[1]"
                  :min="0"
                  :max="100"
                  type="input"
                />
              </VsFormItem>
              <VsFormItem
                class="padding-box-item"
                label="B"
                :rules="genRulesByKey('tooltip.advancedTooltipSetting.padding.[x]')"
              >
                <Range
                  v-model:value="form.advancedTooltipSetting.paddingArr[2]"
                  :min="0"
                  :max="100"
                  type="input"
                />
              </VsFormItem>
              <VsFormItem
                class="padding-box-item"
                label="L"
                :rules="genRulesByKey('tooltip.advancedTooltipSetting.padding.[x]')"
              >
                <Range
                  v-model:value="form.advancedTooltipSetting.paddingArr[3]"
                  :min="0"
                  :max="100"
                  type="input"
                />
              </VsFormItem>
            </div>
          </div>
        </el-form>
        <template #footer>
          <span
            class="advancedSettingDialog-footer"
          >
            <el-button @click.stop="closeAdvancedTooltipDialog">{{ $demoi18n('panel.confirm.cancel') }}</el-button>
            <el-button
              type="primary"
              @click.stop="closeAdvancedTooltipDialog"
            >{{ $demoi18n('panel.confirm.ok') }}</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog
        v-model="originSettingVisiable"
        class="originSettingDialog"
        :title="$demoi18n('panel.tooltipEditor.aativeTooltip')"
        append-to-body
        width="450px"
        :close-on-click-modal="false"
        :class="`${visualThemeClassName} ${xvueNameSpace}`"
        @close="closeOriginTooltipDialog"
      >
        <PanelLabelOverflowTooltip ref="panelLabelOverflowTooltip" />
        <el-form
          v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
          class="prop-form"
          label-position="right"
          label-width="110px"
        >
          <VsFormItem
            :label="$demoi18n('layer.label.bgColor')"
            style="display:flex;align-items:center;"
            :rules="genRulesByKey('tooltip.originTooltipSetting.background')"
          >
            <ColorPicker
              v-model:value="form.originTooltipSetting.background"
              :show-alpha="true"
              @change="colorOriginTootipChange"
            />
          </VsFormItem>
        </el-form>
        <template #footer>
          <span
            class="advancedSettingDialog-footer"
          >
            <el-button @click.stop="closeOriginTooltipDialog">{{ $demoi18n('panel.confirm.cancel') }}</el-button>
            <el-button
              type="primary"
              @click.stop="closeOriginTooltipDialog"
            >{{ $demoi18n('panel.confirm.ok') }}</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import ColorPicker from '@/components/common/color-picker/color-picker.vue';
import HelpManualSnippet from '@/components/common/help-manual/help-manual-snippet.vue';
import HelpManual from '@/components/common/help-manual/help-manual.vue';
import Helptip from '@/components/common/helptip/helptip.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import Range from '@/components/common/range/range.vue';
import TinymceEditor from '@/components/common/tinymce-editor/tinymce-editor.vue';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import EventBus from '@/event-bus/EventBus.js';
import { $demoi18n } from '@/utils/lang';
import { genRulesByKey } from '@/utils/rules';
import { $confirm, dropArrItem, objHas, xssValueFilter } from '@/utils/util.js';
import { nextTick } from 'vue';
import AsTooltipData from './as-tooltip-data.vue';
import TooltipData from './tooltip-data.vue';

export default {
  components: {
    TinymceEditor,
    TooltipData,
    ColorPicker,
    Range,
    Helptip,
    ValueInputer,
    AsTooltipData,
    PanelLabelOverflowTooltip,
    HelpManual,
    HelpManualSnippet,
  },
  inject: {
    configPanelRefs: { default: {} },
  },
  props: {
    btnText: {
      type: String,
      default: $demoi18n('panel.tooltipEditor.btnDefault'),
    },
    config: Object, // 对应具体组件config.js
    tableConfig: Object, // 作为表格tooltips
    vars: Object, // {s:'组'， y1: '值'}
    useFor: String, // tooltip | hover-text, 用于区分用途
    type: String, // '' | echart
    showCorrelation: {
      type: Boolean,
      default: true,
    },
    echartVars: Object,

    // 额外配置，用于悬浮文本
    extraConfig: {
      type: Object,
      default: () => ({}),
    },

    // 左表右xx组件区分图表专用
    curComp: String,

    // api参数存入xvue数组过滤使用
    widgetInstanceId: String,

    // 排除变量，不出现在可插入默认变量中
    excludeVars: Array,
  },
  emits: ['save'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      form: {

        // 待提交的对象，跟组件property.tooltip结构一致
        isVisiable: true, // 高级tooltip
        isOriginVisiable: true, // echart原生tooltip
        isPermil: false, // 数值千分符处理
        html: '',
        apis: [],
        hideDelay: 0, // 浮层隐藏的延迟，单位为s
        advancedTooltipSetting: {
          background: 'rgba(50,50,50,0.7)',
          borderColor: null,
          borderWidth: 0,
          borderStyle: 'solid',
          paddingArr: [5, 5, 5, 5], // 默认各方向的内边距5px：上右下左
        },
        originTooltipSetting: {
          background: null,
        },
        asTooltip: false, // 当前组件作为别的组件的tooltip
        asTooltipKey: '', // 别的组件在tooltip编辑器中用@{xxx}占位，关联当前组件，并兼容以前的#{xxx}用法
        asTooltipUsers: [],
      },
      editorVisiable: false,
      advancedSettingVisiable: false,
      originSettingVisiable: false,
      curApiItem: {},
      dataDialogVisiable: false,
      defaultVars: {},
      demoDetailVisible: false,
      componentStyle: window._adoPremise.uc.theme,

      // 组件级tooltip
      asTooltipDialogVisible: false,
      curAsItem: {},
      xvueTheme: window._adoPremise.uc.theme,
    };
  },
  computed: {
    varsNew() {
      if (this.type === 'echart') {
        if (this.echartVars) {
          return this.echartVars;
        }
        return {
          seriesName: '', // 系列名，'吉利莲'
          name: '', // 可能是x轴名称 '2020-1-1'
          value: '', // 值
        };
      }

      // 如果有传参，取传参
      if (this.vars) {
        return this.vars;
      }

      // 取映射map
      let vars = {}; // {s:'组'， y1: '值'}

      // 取tootlip配置
      let { tooltip } = this.config.config.property;

      // 左表右xx组件特殊处理
      if (this.curComp) {
        tooltip = tooltip[this.curComp];
      }
      if (tooltip && tooltip.vars) {
        vars = tooltip.vars;
      } else {
        let { data } = this.config.config;
        if (this.curComp) {
          data = data[this.curComp];
        }
        if (data && data.tableData) {
          data.tableData.forEach(n => {
            vars[n.field] = n.explain;
          });
        }
      }

      // 排除变量
      if (this.excludeVars) {
        this.excludeVars.forEach(key => {
          delete vars[key];
        });
      }

      return vars;
    },
    dataDialogTitle() {
      return this.curApiItem && this.curApiItem.dataSourceType ?
        this.$demoi18n('panel.tooltipEditor.edit.dialogTitle') :
        this.$demoi18n('panel.tooltipEditor.add.dialogTitle');
    },
    asTooltipDialogTitle() {
      return this.$demoi18n('panel.label.component.tooltipTitle');
    },
    isAsTooltipOptShow() {
      // 关系气泡图单独设置高级tooltip时隐藏
      if (this.extraConfig.position === 'table-config') {
        return false;
      }
      const { canAsTooltip } = this.config.config.property;
      return canAsTooltip && this.useFor !== 'hover-text';
    },
    newAsItemBtnShow() {
      // 坐表右甘特，左表右形状有两个tooltip对象，不兼容组件级tooltip，隐藏入口
      const arr = [`config_${process.env.xvueNameSpace_}table_gantt_chart`, `config_${process.env.xvueNameSpace_}table_shape_chart`];
      return !arr.includes(this.config.propertyPannelName);
    },
    compKey() {
      let key = this.config.propertyPannelName.replace(`config_${process.env.xvueNameSpace_}`, '');
      switch (this.curComp) {
        case 'table':
          key = 'single_header_page_table';
          break;
        case 'gantt':
          key = 'gantt_chart';
          break;
        case 'shape':
          key = 'shape_chart';
          break;
        default: break;
      }
      return key;
    },
  },
  watch: {
    editorVisiable(visible) {
      if (visible) {
        document
          .getElementsByTagName('body')
          .item(0)
          .appendChild(this.$refs.popBox);
      } else {
        this.$refs.tooltipEditor.appendChild(this.$refs.popBox);
      }
    },
  },
  created() {
    this.init();
    if (this.useFor === 'hover-text') {
      EventBus.$on('hoverTextPop', () => {
        this.openEditor();
      });
    }
  },
  beforeUnmount() {
    EventBus.$off('hoverTextPop');
  },
  methods: {
    genRulesByKey,
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    openTooltipData() {
      nextTick(() => {
        this.$refs['tooltip_data'] && this.$refs['tooltip_data'].openDialog();
      });
    },
    async init() {
      let config;
      if (this.extraConfig.position === 'panel-data') {
        config = this.config.config.data.tooltip;
        config.html = xssValueFilter(config.html);
      } else if (this.extraConfig.position === 'table-config') {
        config = this.tableConfig.tooltip;
      } else {
        config = this.config.config.property.tooltip;
        if (config) {
          config.html = xssValueFilter(config.html);
        }

        // 左表右xx组件特殊处理
        if (this.curComp) {
          config = config[this.curComp];
        }
      }

      if (config) {
        this.form = {
          ...this.form,
          ...JSON.parse(JSON.stringify(config)),
        };

        if (objHas(config, 'html')) {
          this.form.html = xssValueFilter(config.html);
        }

        if (objHas(config, 'advancedTooltipSetting')) {
          if (!objHas(this.form.advancedTooltipSetting, 'paddingArr')) {
            this.form.advancedTooltipSetting.paddingArr = [5, 5, 5, 5];
          }
        }
      }
    },
    openEditor() {
      this.editorVisiable = true;
    },
    saveEditor(html) {
      this.form.html = xssValueFilter(html);
      this.editorVisiable = false;
      if (this.extraConfig.position === 'table-config') {
        this.tableConfig.tooltip = this.form;
        this.tableConfig.tooltip.isSaved = true;
      } else {
        this.$emit('save', this.form);
      }
    },
    cancelEditor() {
      this.editorVisiable = false;
    },
    insertText(text) {
      this.$refs?.TinymceEditor?.editor?.insertContent(text);
    },
    newApiItem() {
      this.curApiItem = {}; // 设置null的话tooltip-data watch不到变化
      this.dataDialogVisiable = true;
    },
    editApiItem(item) {
      this.curApiItem = item;
      this.dataDialogVisiable = true;
    },
    delApiItem(item) {
      $confirm(this.$demoi18n('message.confirmDelte'), this.$demoi18n('popup.title.tips'), {
        confirmButtonText: this.$demoi18n('btn.confirm'),
        cancelButtonText: this.$demoi18n('btn.cancel'),
        type: 'warning',
      }).then(() => {
        this.form.apis = dropArrItem(this.form.apis, item);
      });
    },
    saveApiItem(item) {
      const _item = JSON.parse(JSON.stringify(item));
      if (Object.keys(this.curApiItem).length !== 0) {
        // 编辑模式
        const index = this.form.apis.indexOf(this.curApiItem);
        this.form.apis[index] = _item;
      } else {
        this.form.apis.push(_item);
      }
      this.dataDialogVisiable = false;
    },
    cancelApiItem() {
      this.curApiItem = {};
      this.dataDialogVisiable = false;
    },

    // 获取数据页签配置的变量
    getVarsByPanelData() {
      const panelData = this.configPanelRefs.panel_data;

      // 左表右xx组件特殊处理
      let dataForm = panelData.form;
      if (this.curComp) {
        dataForm = dataForm[this.curComp];
      }

      const defaultVars = {};

      if (dataForm.dataSourceType !== 'xMiner') {
        return;
      }

      dataForm.tableData.forEach(item => {
        if (item.mapping) {
          const option = panelData.mappingOptions.find(o => o.option_value === item.mapping);
          if (option) {
            defaultVars[item.mapping] = option.option_label;
          }
        }
      });

      this.defaultVars = defaultVars;
    },
    colorChange(color) {
      this.form.advancedTooltipSetting.background = color;
    },
    colorOriginTootipChange(color) {
      this.form.originTooltipSetting.background = color;
    },
    closeAdvancedTooltipDialog() {
      const { advancedTooltipSetting: { paddingArr } = {} } = this.form || {};
      if (paddingArr && paddingArr.length > 0) {
        const padding = paddingArr.map(ele => `${ele || 0}px`).join(' ');
        this.form.advancedTooltipSetting.padding = padding;
      }
      this.advancedSettingVisiable = false;
    },
    closeOriginTooltipDialog() {
      this.originSettingVisiable = false;
    },
    newAsItem() {
      this.curAsItem = {};
      this.asTooltipDialogVisible = true;
    },
    editAsItem(item) {
      this.curAsItem = item;
      this.asTooltipDialogVisible = true;
    },
    delAsItem(item) {
      $confirm(this.$demoi18n('message.confirmDelte'), this.$demoi18n('popup.title.tips'), {
        confirmButtonText: this.$demoi18n('btn.confirm'),
        cancelButtonText: this.$demoi18n('btn.cancel'),
        type: 'warning',
      }).then(() => {
        this.form.asTooltipUsers = dropArrItem(this.form.asTooltipUsers, item);
      });
    },
    saveAsItem(item) {
      const _item = JSON.parse(JSON.stringify(item));
      if (Object.keys(this.curAsItem).length !== 0) {
        // 编辑模式
        const index = this.form.asTooltipUsers.indexOf(this.curAsItem);
        this.form.asTooltipUsers[index] = _item;
      } else {
        this.form.asTooltipUsers.push(_item);
      }
      this.asTooltipDialogVisible = false;
    },
    cancelAsItem(item) {
      this.curAsItem = {};
      this.asTooltipDialogVisible = false;
    },
  },
};
</script>
<style lang="less">
.pop-box.dialog_style_dark.for_tooltip,
.pop-box.dialog_style_dark.for_hover-text {
  .ql-container {
    background-color: rgba(53, 83, 107, 0.7);
    color: #fff;
  }
}
.pop-box.dialog_style_light.for_tooltip,
.pop-box.dialog_style_light.for_hover-text {
  .ql-container {
    background-color: rgba(34, 34, 34, 0.7);
    color: #fff;
  }
}
.advancedSettingDialog,
.originSettingDialog {
  .el-form-item__content {
    margin-left: 0 !important;
  }
  .el-form-item__label {
    width: 130px !important;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }
  .el-dialog__footer {
    text-align: center;
  }
  .padding-box-item {
    display: flex;
    width: 40%;
    margin: 0 5% 10px 0;
    align-items: center;
    .el-form-item__label {
      width: 12px !important;
      padding: 0 2px 0 0;
      overflow-x: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .padding-box-item-label {
      padding: 0 10px 0 0;
    }
  }
}
</style>
<style lang="less" scoped>
.tooltip-editor {
  line-height: normal;
  display: inline-block;
}
// .pop-box {
  // :deep(.tip) {
  .tip {
    padding: 10px;
    background-color: #eaeaea;
    margin-bottom: 10px;
    border: 1px solid #ddd;
    font-size: 11px;
    line-height: 18px;
    .switch {
    }
    .top-btn {
      display: flex;
      margin-bottom: 10px;
    }
    .var {
      margin: 0 3px;
      display: inline-block;
      padding: 1px 5px 4px 5px;
      color: #fff;
      cursor: pointer;
      border-radius: 3px;
      background-color: #74badf;
      line-height: 20px;
      height: 18px;
      &:hover {
        background-color: #00aaff;
        color: #fff;
      }
      i {
        color: red;
        font-style: normal;
        color: #baf4c3;
      }
    }
    .row-box {
      background-color: #fff;
      display: flex;
      justify-content: space-between;
      align-items: center;
      border: 1px solid #ddd;
      margin-top: -1px;
      .label {
        width: 80px;
        text-align: right;
        padding-left: 10px;
        padding-right: 5px;
        box-sizing: content-box;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      .cont {
        flex: 1;
        border-left: 1px solid #ddd;
        padding: 10px;
        min-height: 30px;
        .info {
          margin-left: 10px;
          font-size: 11px;
          color: #4e8371;
          vertical-align: middle;
        }
        .advancedSetting,
        .originSetting {
          color: #409eff;
          font-size: 16px;
          float: right;
          cursor: pointer;
          & > i,
          & > span {
            vertical-align: middle;
          }
          & > i {
            margin-right: 5px;
          }
        }
      }
    }
    .default-vars {
    }
    .add-api-item {
      padding: 3px 8px;
      font-size: 11px;
      margin-right: 10px;
      width: 63px;
      height: 21px;
    }
    .add-api-item-fr {
      float: right;
    }
    .api-vars,
    .asTooltipUsers {
      .api-item,
      .as-item {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        .api-message {
          line-height: 24px;
          .api-message-label {
          }
          .api-message-value {
            padding-right: 20px;
            padding-left: 5px;
          }
        }
        .data-correlation {
          line-height: 24px;
          .correlate {
            display: inline-block;
            line-height: normal;
            .correlate-item {
              padding-right: 10px;
            }
            .priKey {
              margin: 0 1px;
              display: inline-block;
              padding: 2px 5px;
              color: #666;
              border-radius: 3px;
              i {
                font-style: normal;
                color: #baf4c3;
              }
            }
            .symbol {
              font-weight: bolder;
              font-size: 17px;
            }
            .priMapKey {
              margin: 0 1px;
              display: inline-block;
              padding: 2px 5px;
              color: #666;
              border-radius: 3px;
              i {
                font-style: normal;
                color: #baf4c3;
              }
            }
          }
        }
        .inner {
          display: flex;
          justify-content: flex-start;
          align-items: center;
          flex-wrap: wrap;
          height: 100%;
          padding: 3px 0;
        }
        .tool {
          flex-shrink: 0;
          position: absolute;
          right: 5%;
        }
      }
    }
    .demo {
      margin-top: 10px;
      .code {
        background-color: #fff;
        color: #848484;
        margin: 5px 0;
        border: 1px solid #ddd;
        font-size: 11px;
        padding: 10px;
        .expand_btn {
          position: relative;
          top: 2px;
          cursor: pointer;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          margin-top: 10px;
          th,
          td {
            padding: 0 5px;
            font-weight: 400;
          }
          th {
            text-align: right;
            color: #606266;
            width: 120px;
            vertical-align: top;
            white-space: nowrap;
          }
        }
      }
    }
  }
  .btns {
    margin-top: 10px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 32px;
  }
// }

.dialog_style_dark {
  :deep(.el-dialog__header) {
    background: #183c5a;
    .el-dialog__title {
      font-size: 16px;
      color: #fff;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }
  }

  :deep(.el-dialog__body) {
    background: #0e2b40;
    .tip {
      padding: 0;
      border: unset;
      background-color: unset;
      .row-box {
        border: unset;
        background-color: #0a2336;
        color: #98cae6;
        .cont {
          border: unset;

          .var {
            border: 1px solid #219fff;
            color: #00aaff;
            background-color: unset;
            padding: 2px 5px;
            height: unset;
            line-height: unset;
          }
        }

        .el-switch__core {
          background-color: #064559;
          border-color: #064559;
        }

        .el-switch.is-checked {
          .el-switch__core {
            background-color: #0eb4c2;
            border-color: #0eb4c2;
          }
        }
      }
    }

    .demo {
      .code {
        background-color: #0a2336;
        color: #98cae6;
        border: unset;
        table {
          th {
            color: #fff;
          }
        }
      }
    }

    // 添加/删除变量弹窗
    @font_color_dark: #98cae6;
    @font_color_active_dark: #00f0ff;
    @background_color_dark: #071f30;
    @bgColor_dark: #000c17;
    @borderColor_dark: #116584;
    @textColor_dark: #ffffff;
    .tooltip-data {
      .el-form-item__label {
        color: @font_color_dark;
      }
      .el-form-item__content {
        .el-input {
          .el-input__inner {
            border-color: @borderColor_dark;
            color: @textColor_dark;
            background-color: @bgColor_dark;
          }

          .el-input__icon {
            color: @borderColor_dark;
          }
        }

        .el-radio-group {
          .el-radio {
            color: @textColor_dark;

            .el-radio__input {
              .el-radio__inner {
                border-color: @font_color_active_dark;
                background-color: unset;
              }
            }

            .is-checked {
              .el-radio__inner {
                &::after {
                  background-color: @font_color_active_dark;
                }
              }
            }

            .el-radio__label {
              color: #fff;
            }
          }
        }

        // 表格
        .config-panel-table {
          color: @font_color_dark;
          background-color: @background_color_dark;

          &::before {
            background-color: @background_color_dark;
          }

          .cell {
            padding: 0 3px !important;
          }
          td,
          th {
            padding: 5px 0 !important;
          }

          .el-table__header {
            th {
              background-color: #122b40 !important;
              border-color: #122b40;
              color: @font_color_dark;
            }
          }

          .el-table__body {
            tr {
              td {
                background-color: @background_color_dark;
                border-color: @background_color_dark;

                .icon-library-open {
                  background-color: unset;
                  border-color: #0eb4c2;
                }
              }
            }
          }

          .el-table__empty-block {
            background-color: #093758;

            .el-table__empty-text {
              color: @font_color_active_dark;
            }
          }
        }
      }

      :deep(.el-loading-mask) {
        background-color: rgba(0, 0, 0, 0.72);
      }
    }

    .editor-box {
      .ql-toolbar {
        .ql-picker {
          color: #fff;
        }
        .ql-picker-options {
          background-color: #102e4f;
          color: #fff;
          .ql-selected {
          }
          /* *滚动条* */
          &::-webkit-scrollbar {
            width: 4px !important;
            height: 4px !important;
          }

          &::-webkit-scrollbar-thumb {
            /* 滚动条里面小方块 */
            background: #00f0ff !important;
          }

          &::-webkit-scrollbar-track {
            /* 滚动条里面轨道 */
            background: #1a405f !important;
          }

          &::-webkit-scrollbar-corner {
            background-color: #1a405f !important;
          }
        }

        .ql-stroke {
          stroke: #fff;
        }

        .ql-fill {
          fill: #fff;
        }

        button {
          &:hover {
            fill: unset;
          }
        }
      }

      .ql-snow {
        border-color: #116584;
        .ql-picker-label {
          &:hover {
            color: @font_color_active_dark;
          }
        }
        .ql-picker-item {
          &:hover {
            color: @font_color_active_dark;
          }
        }
        .ql-selected {
          color: @font_color_active_dark;
        }
        .ql-active {
          color: @font_color_active_dark;
        }
      }
    }

    // 默认按钮样式类
    .btn-sure {
      background-color: #0eb4c2;
      border-color: #0eb4c2;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }

    .button-cancel {
      background-color: #064559;
      border-color: #064559;
      color: #fff;

      .el-icon-circle-plus {
        color: #fff;
      }
    }
  }
}
.dialog_style_light {
  :deep(.el-dialog__body) {
    .editor-box {
      .ql-toolbar {
        .ql-picker-options {
          /* *滚动条* */
          &::-webkit-scrollbar {
            width: 4px !important;
            height: 4px !important;
          }

          &::-webkit-scrollbar-thumb {
            /* 滚动条里面小方块 */
            background: #65c7f8 !important;
          }

          &::-webkit-scrollbar-track {
            /* 滚动条里面轨道 */
            background: #efefef !important;
          }

          &::-webkit-scrollbar-corner {
            background-color: #efefef !important;
          }
        }
      }
    }
  }
}
</style>
